import { Response, NextFunction } from "express";
import { verifyToken } from "../utils/jwt";
import Types from "../typings";

// 无需权限白名单
const unAuthUrl: string[] = [
  "/api/login",
  "/api/logout",
  "/api/user/add",
  "/api/file/upload",
  "/api/file/delete",
  "/api/file/check",
  "/api/test/common",
];

const authMiddle = async (
  req: Types.Express.ConvertRequest,
  res: Response,
  next: NextFunction
) => {
  const { authorization } = req.headers;

  const requestUrl = req.originalUrl.split("?")[0];

  console.log("=================", req.originalUrl);

  const isInWhiteList = unAuthUrl.includes(requestUrl);

  // 上传文件无需权限允许查看
  const isUploadFile = req.originalUrl.includes("/uploads/");

  // 静态文件无需权限允许查看
  const isPublicFile = req.originalUrl.includes("/public/");

  // 用户失去登录状态，告知用户没有权限进入系统，需要重新登录
  if (!authorization && !isInWhiteList && !isUploadFile && !isPublicFile) {
    res.status(401).send("当前用户已失去登录状态，请重新登录");
    return;
  }

  if (authorization && !["/api/login"].includes(requestUrl)) {
    try {
      const user = await verifyToken(authorization);
      // jwt 解析后挂在用户信息到 req
      req.loginUser = user || {};
    } catch (err) {
      console.log(err);
      return res.status(401).send();
    }
  }

  next();
};

export default authMiddle;
